﻿//-----------------------------------------------------------------------
// <copyright file="AsADistributorAdministratorWhenICreateATenantIShouldAutomaticallyHaveCreatedATenantAdministrator.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Utility.Tests.UI.Web.Behaviour.Tenant{    using System.Linq;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Kernel.Factories;
    using AbstractSaaSTemplate.UI.Web.Controllers;
    using AbstractSaaSTemplate.UI.Web.Models.Tenant;
    using AbstractSaaSTemplate.UI.Web.Models.User;
    using AbstractSaaSTemplate.Utility.Tests.UI.Utilities;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// @14076807
    /// Como Administrador de Distribuidor, ao criar um novo Tenant, eu deveria
    /// ter um Usuário Administrador do Tenant ao criar um Tenant.
    /// </summary>
    [TestClass]
    public class TestFor0014076807
    {
        #region Properties

        /// <summary>
        /// Gets or sets the User controller which will be used in tests.
        /// </summary>
        private UserController UserController { get; set; }
        
        /// <summary>
        /// Gets or sets the Tenant controller which will be used in tests.
        /// </summary>
        private TenantController TenantController { get; set; }

        #endregion

        #region Setup

        /// <summary>
        /// This method initializes controllers and dependencies for run tests.
        /// </summary>
        [TestInitialize]
        public void Setup()
        {
            TestFor0013453151.EnsureInstallationIsComplete();
            
            var factory = new ApplicationFactory();

            this.UserController = factory.CreateControllerFor<UserController>();
            this.TenantController = factory.CreateControllerFor<TenantController>();
        }

        #endregion

        /// <summary>
        /// @14076807
        /// Como Administrador de Distribuidor, ao criar um novo Tenant, eu deveria
        /// ter um Usuário Administrador do Tenant ao criar um Tenant.
        /// "Gerenciamento de Licenciados"
        /// Passos da Mímica --------------------------------------------------
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// 2.  Criar um tenant licenciado.
        ///     Deve assegurar:
        ///     2.1) Que o tenant foi criado.
        ///     2.2) Que um usuário administrador foi criado para o Tenant.
        /// </summary>
        [TestMethod]
        public void AsADistributorAdministratorWhenICreateATenantIShouldAutomaticallyHaveCreatedATenantAdministrator()
        {
            /* =========================================================
             * EXECUÇÃO DA MÍMICA
             * =========================================================
             * Os procedimentos executados à seguir são uma mímica dos
             * procedimentos executados pelos usuários no uso real do sistema.
             * ========================================================= */

            // 1)
            this.LogOnAndAssertActiveUser();

            // 2)
            this.AssertThatCreateTenantCreatesAdministrator();
        }

        /// <summary>
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// </summary>
        private void LogOnAndAssertActiveUser()
        {
            this.UserController.MockForTesting("LogOn", HttpVerbs.Post);
            var distributorAdmin = this.UserController.RepositoryForMembership
                .GetUsersByRole(AccessLevels.Distributor, AccessRoles.Administrator)
                .FirstOrDefault();

            this.UserController.LogOn(
                new LogOnForm()
                {
                    Login = distributorAdmin.Credentials.Login,
                    Password = distributorAdmin.Credentials.RetrievePassword()
                },
                string.Empty);

            var activeUser = this.UserController.ServiceForMembership.ActiveUser;
            Assert.IsNotNull(activeUser);
        }
        
        /// <summary>
        /// 2.  Criar um tenant licenciado.
        ///     Deve assegurar:
        ///     2.1) Que o tenant foi criado.
        ///     2.2) Que um usuário administrador foi criado para o Tenant.
        /// </summary>
        private void AssertThatCreateTenantCreatesAdministrator()
        {
            // data for create a tenant
            var model = new CreateOrEditTenantForm();
            model.KeyOrLocation = "test-admin-tenant";
            model.AdministratorEmailAddress = "admin-of-tenant-14076807@tenant.com";
            model.AdministratorFirstName = "14076807-firstname";
            model.AdministratorLastName = "14076807-lastname";
            model.BillingAddressCity = "14076807-city";
            model.BillingAddressCountryCode = "10";
            model.BillingAddressLine1 = "14076807-b-line1";
            model.BillingAddressLine2 = "14076807-b-line2";
            model.BillingAddressLine3 = "14076807-b-line3";
            model.BillingAddressPostalCode = "099990410";
            model.BillingAddressState = "14076807-b-state";
            model.CompanyName = "14076807-companyname";
            model.ContactAddressCity = "14076807-b-city";
            model.ContactAddressCountryCode = "10";
            model.ContactAddressLine1 = "14076807-c-line1";
            model.ContactAddressLine2 = "14076807-c-line2";
            model.ContactAddressLine3 = "14076807-c-line3";
            model.ContactAddressPostalCode = "099990410";
            model.ContactAddressState = "14076807-c-state";
            model.ContactPhoneAreaCode = "99";
            model.ContactPhoneExtension = "999";
            model.ContactPhoneNumber = "99999999";
            model.ContactUsesTheSameAddressAsBilling = false;
            model.DisplayName = "14076807-displayname";

            // Clear model state for perform new test.
            this.TenantController.ModelState.Clear();

            // Mock controller.
            this.TenantController.MockForTesting("CreateOrEditTenant", HttpVerbs.Post);

            // Perform create tenant.
            var actionResult = this.TenantController.CreateOrEditTenant(null, model);

            // Check validation.
            Assert.IsTrue(this.TenantController.ModelState.IsValid);

            // Assert that action return redirect.
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));

            // Get tenants from tenant repository.
            var tenants = this.TenantController
                .RepositoryForTenancy
                .Tenants
                .Where(d =>
                    d.Website == model.Website &&
                    d.DisplayName == model.DisplayName &&
                    d.CompanyName == model.CompanyName &&

                    d.ContactPhone.AreaCode == model.ContactPhoneAreaCode &&
                    d.ContactPhone.Number == model.ContactPhoneNumber &&
                    d.ContactPhone.Extension == model.ContactPhoneExtension &&

                    d.BillingAddress.Line1 == model.BillingAddressLine1 &&
                    d.BillingAddress.Line2 == model.BillingAddressLine2 &&
                    d.BillingAddress.Line3 == model.BillingAddressLine3 &&
                    d.BillingAddress.City == model.BillingAddressCity &&
                    d.BillingAddress.State == model.BillingAddressState &&
                    d.BillingAddress.CountryCode == model.BillingAddressCountryCode &&
                    d.BillingAddress.PostalCode == model.BillingAddressPostalCode &&

                    d.ContactAddress.Line1 == model.ContactAddressLine1 &&
                    d.ContactAddress.Line2 == model.ContactAddressLine2 &&
                    d.ContactAddress.Line3 == model.ContactAddressLine3 &&
                    d.ContactAddress.City == model.ContactAddressCity &&
                    d.ContactAddress.State == model.ContactAddressState &&
                    d.ContactAddress.CountryCode == model.ContactAddressCountryCode &&
                    d.ContactAddress.PostalCode == model.ContactAddressPostalCode)
                .ToList();

            // Check if tenant was created.
            Assert.IsTrue(tenants.Count() == 1);

            // we grab the tenant to check the repository for
            // the userTenant association that is related to it.
            var tenant = tenants.FirstOrDefault();
            var administrators = this.TenantController.RepositoryForMembership.GetUsersByTenantIdAndRole(
                tenant.Id,
                Domain.Models.Enumerators.AccessRoles.Administrator);

            // Checks if the administrator user exists.
            Assert.AreEqual<int>(1, administrators.Count());
        }
    }
}


